package medium搜索二维矩阵;

public class Solution {
    public boolean searchMatrix1(int[][] matrix, int target) {

        int row = matrix.length;
        int column = matrix[0].length;
        int n = Math.min(row, column);

        for (int i = 0; i < n; i++) {
            if (matrix[i][i] > target) {
                return false;
            } else if (matrix[i][i] == target) {
                return true;
            } else {
                for (int j = i + 1; j < row; j++) {
                    if (target == matrix[j][i])
                        return true;
                }
                for (int k = i + 1; k < column; k++) {
                    if (target == matrix[i][k])
                        return true;
                }
            }
        }
        return false;
    }

    //折半
    public boolean searchMatrix2(int[][] matrix, int target) {
        for (int[] row : matrix) {
            int index = search(row, target);
            if (index >= 0) {
                return true;
            }
        }
        return false;
    }

    public int search(int[] nums, int target) {
        int low = 0, high = nums.length - 1;
        while (low <= high) {
            int mid = (high - low) / 2 + low;
            int num = nums[mid];
            if (num == target) {
                return mid;
            } else if (num > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }

    //z字查找
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length, n = matrix[0].length;
        int x = 0, y = n - 1;
        while (x < m && y >= 0) {
            if (matrix[x][y] == target) {
                return true;
            }
            if (matrix[x][y] > target) {
                --y;
            } else {
                ++x;
            }
        }
        return false;
    }
}
